// ==UserScript==
// @name        auto repeat - openai.com
// @namespace   Violentmonkey Scripts
// @match       https://chat.openai.com/*
// @grant       none
// @version     1.0
// @author      Dillon
// @description 2023/6/12 22:00:54
// ==/UserScript==

(function() {
    'use strict';

    window.addEventListener('load', function() {
        console.log('load auto repeat js')

        const sendButton = document.querySelector('button.absolute');
        const sendTextarea = document.getElementById('prompt-textarea');
        console.log(`sendButton: ${sendButton}`);
        console.log(`sendTextarea: ${sendTextarea}`);

        const config = { attributes: true, childList: true, subtree: true };

        const callback = function(mutationsList, observer) {
            for(let mutation of mutationsList) {
                if (mutation.type === 'attributes' && mutation.attributeName === 'disabled') {
                    console.log('Button attribute changed...');
                    if (!sendButton.disabled){
                        console.log('ChatGPT response is complete. Sending next command...');
                        // 设置textarea的值
                        let nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
                        nativeInputValueSetter.call(sendTextarea, 'please continue without repeat');

                        let ev2 = new Event('input', { bubbles: true});
                        sendTextarea.dispatchEvent(ev2);

                        // 创建一个新的'keydown'事件
                        // 延迟一段时间，然后模拟Enter键和点击事件
                        setTimeout(function() {
                            // 创建并触发一个键盘事件
                            let event = new KeyboardEvent('keydown', {
                                key: 'Enter'
                            });
                            sendTextarea.dispatchEvent(event);
                            sendTextarea.dispatchEvent(event);

                            // 点击按钮
                            sendButton.click();
                        }, 1000);  // 1000毫秒，或者1秒
                    }
                }

                if (mutation.type === 'childList') {
                    let targetNode = document.querySelector('div.text-2xl');
                    if (!targetNode) {
                        console.log('Target node is missing...');
                        sendButton.disabled = false;
                    }
                }
            }
        };

        const observer = new MutationObserver(callback);

        observer.observe(document.body, config);
    });
})();